<?php
class ControllerCatalogProductTpl extends AdminController {
	public function index() {
		M("catalog/product_tpl");
		$this->getList();
	}

	public function insert() {
		M("catalog/product_tpl");
		if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_product_tpl->addTemplate($this->request->post);
			
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/product_tpl'));
		}
		
		$this->getForm();
	}
	public function update() {
		M("catalog/product_tpl");
		if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_product_tpl->updateTemplate($this->request->get['template_id'], $this->request->post);
			
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/product_tpl'));
		}
		$this->getForm();
	}

	public function delete() {
		M("catalog/product_tpl");
		if (isset($this->request->post['selected'])) {
			$this->model_catalog_product_tpl->deleteTemplate($this->request->post['selected']);
			
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA("catalog/product_tpl"));
		}
		$this->getList();
	}
	
	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);
		
		$qf = new Query_filter();
		$this->data['templates'] = $this->model_catalog_product_tpl->getTemplates($qf, $total);

		$this->data['pagination'] = $this->pagination($total)->render();
		
		$this->display('catalog/product_tpl_list.tpl');
	}
	
	protected function getForm() {
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');
		$this->document->setTitle($this->_['heading_title']);
		
		$template_id = G('template_id', 0);
		
		if ($template_id) {
			$this->data['action'] = UA('catalog/product_tpl/update', 'template_id=' . $template_id);
			if (!$this->request->isPost()) {
				$this->vo->data = $this->model_catalog_product_tpl->getTemplate($template_id);
			}
		}
		else {
			$this->data['action'] = UA('catalog/product_tpl/insert');
		}
		$this->display('catalog/product_tpl_form.tpl');
	}
	
	protected function validateForm() {
		$this->load->library('form_validation', true);
		$this->form_validation->set_rules('title', '', 'required|range_length[3,100]', $this->_['error_name']);
		return $this->form_validation->run();
	}
	
	public function ls() {
		M("catalog/product_tpl");
		$qf = new Query_filter(null, false);
		$qf->set('filter_status', 1);
		$templates = $this->model_catalog_product_tpl->getTemplates($qf, $total);
		$this->response->setOutput(json_encode($templates));
	}

	public function get() {
		$template_id = G('template_id', 0);
		M("catalog/product_tpl");
		$template = $this->model_catalog_product_tpl->getTemplate($template_id);
		$this->response->setOutput(html_entity_decode($template['content']));
	}
}